// 和用户相关的路由地址 
const express = require("express");
const path = require("path")
const md5 = require("md5")
const userModel = require("../models/usermodel.js")
let router = express.Router();
//1.安装formidable模块
//2.引入formidable模块
//3.实例化且配置 formidable模块
// const formidable = require("formidable");

let { uploadimg } = require('../util')//他会自动读取uitl文件下的index.js

router.get("/getdata", async (req, res) => {
    console.log("user/getdata请求进来");

    try {
        //查找数据库user数据列表
        //后端分页逻辑
        //一。计算页码，把页码传给前端
        let usersData = await userModel.find();
        //数据总条数
        let totalCount = usersData.length;
        //每页显示条数
        let perpage = 3;
        //计算页码
        let pageCount = Math.ceil(totalCount / perpage);


        //根据前端传递的页码返还对应的数据
        //接收前端传递的页码；
        let p = req.query;
        console.log(p);
        // 根据页码 查询对应的数据
        let filterData = await userModel.find().skip((p - 1) * perpage).limit(perpage);

        res.json({
            info: "获取用户信息成功",
            pageCount,
            status: 1,
            users: filterData
        })
    } catch (error) {
        res.json({
            info: "获取用户信息失败",
            status: 0,
            err
        })
    }

})

router.delete("/deleuser", async (req, res) => {
    console.log("删除请求进来了");
    let { _id } = req.query;
    console.log(_id);
    try {
        let resobj = await userModel.deleteOne({ _id });
        console.log(resobj, "resobj");
        res.json({
            info: "删除成功",
            status: 1,
            resobj
        })
    } catch (error) {
        res.json({
            info: "删除失败",
            status: 1,
            error
        })
    }

})

router.post("/adduser", async (req, res) => {
    try {
        let reslut = await uploadimg(req);
        console.log(reslut, "result");
        reslut.pwd = md5(reslut.pwd);
        reslut.time = new Date().toLocaleDateString();
        console.log(reslut, "midle");
        //    把密码加密之后添加到数据库
        let resobj = await userModel.create(reslut);
        console.log(resobj, "res");
        res.json({
            info: "添加用户成功",
            status: 1
        })
    } catch (err) {
        res.json({
            info: "添加用户失败",
            status: 0,
            err
        })
    }
})

module.exports = router;